package com.day3sockettest.QQChat;

import java.io.*;
import java.net.Socket;

public class ServerThread extends Thread{

    private Socket socket;
    private ServerChatMain serverChatMain;
    public ServerThread(Socket socket,ServerChatMain serverChatMain){
        this.socket = socket;
        this.serverChatMain = serverChatMain;
    }
    BufferedReader br = null;
    @Override
    public void run() {
        String str = null;
        try {
            br = new BufferedReader(new InputStreamReader( socket.getInputStream()));

            while (!(str=br.readLine()).equals("exit")){
            //告诉客户端收到了xx消息
                String msg = socket +":"+str;
                ServerThread.sendMegToAllClient(msg);
                this.serverChatMain.getJta().append(msg+System.lineSeparator());
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //给所有用户广播消息
    public static void sendMegToAllClient(String msg){
        BufferedWriter bw;
        for (Socket socket : ServerChatMain.allSocket){
            try {
                bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                bw.write(msg);
                bw.newLine();//换行发送
                bw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(socket);
        }
    }
}
